package com.wh1200.mybatis

import com.wh1200.mybatis.service.AuditInfoService
import com.wh1200.mybatis.service.TestTenantProvider
import com.wh1200.mybatis.xmlless.plugin.CurrentUserInterceptor
import com.wh1200.mybatis.xmlless.plugin.SpringPagePlugin
import com.wh1200.mybatis.service.XmllessTenantLineHandler
import com.baomidou.mybatisplus.annotation.DbType
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor
import org.mybatis.spring.annotation.MapperScan
import org.springframework.beans.factory.ObjectProvider
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.context.annotation.Bean
import org.springframework.core.annotation.Order

/**
 * 测试程序入口
 *
 * @author 吴昊
 * @since 0.0.1
 */
@SpringBootApplication
@MapperScan("com.wh1200.xmlless.test.dao")
class MybatisTestApplication {

  companion object {
    @JvmStatic
    fun main(args: Array<String>) {
      SpringApplication.run(MybatisTestApplication::class.java, *args)
    }
  }

  @Bean
  fun tenantProvider(): TestTenantProvider {
    return TestTenantProvider()
  }

  @Bean
  fun auditInfoSupplier(): CurrentUserInterceptor {
    return CurrentUserInterceptor(AuditInfoService())
  }

  /**
   * 添加分页插件
   */
  @Bean
  @Order(100)
  fun mybatisPlusInterceptor(
      tenantProvider: ObjectProvider<TestTenantProvider>
  ): MybatisPlusInterceptor {
    val interceptor = MybatisPlusInterceptor()
    if (tenantProvider.ifAvailable != null) {
      interceptor.addInnerInterceptor(
          TenantLineInnerInterceptor(
              XmllessTenantLineHandler(tenantProvider.ifAvailable!!)
          )
      )
    }
    //如果配置多个插件,切记分页最后添加
    interceptor.addInnerInterceptor(SpringPagePlugin(DbType.MYSQL)) //如果配置多个插件,切记分页最后添加
    return interceptor
  }

}
